﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MyAuthCore.Api.Filters;
using MyAuthCore.Entity;
using MyAuthCore.Entity.Beans;
using MyAuthCore.Model.Beans;
using MyAuthCore.Tools;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MyAuthCore.Api.Controllers
{
    public class HomeController: Controller
    {
        public JsonResult Login(User user)
        {
            ResponseResult result = new ResponseResult();
            try
            {
                var ret = SqlSugarHelper.DB.Queryable<User>().Where(it => it.Account == user.Account && it.Password == user.Password).First();
                if (ret == null)
                {
                    result.Message = "用户不存在";
                    result.Code = StateCode.Error;
                    return Json(result);
                }
                string token = TokenHelper.CreateToken(user.Account);
                this.HttpContext.Session.SetString(user.Account, token);
                return Json(token);
            }
            catch (Exception ex)
            {
                result.Message = ex.ToString();
                result.Code = StateCode.Error;
                return Json(result);
            }
        }
        public JsonResult Logout(User user)
        {
            ResponseResult result = new ResponseResult();
            if (string.IsNullOrEmpty(user.Account))
            {
                result.Message = "退出失败";
                result.Code = StateCode.Error;
                return Json(result);
            }
            result.Message = "退出成功";
            result.Code = StateCode.Success;
            this.HttpContext.Session.Remove(user.Account);
            return Json(result);
        }
    }
}
